package com.lilong.jwt.controller;

import com.lilong.jwt.common.base.BaseController;
import com.lilong.jwt.common.util.ResultBean;
import com.lilong.jwt.common.util.ResultUtil;
import com.lilong.jwt.entity.user.User;
import com.lilong.jwt.service.AuthService;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class AuthController extends BaseController {

    @Resource
    private AuthService authService;

    @PostMapping(value = "/auth/login")
    public ResultBean createAuthenticationToken(
            String username, String password) {
        final String token = authService.login(username, password);
        return ResultUtil.SUCCESS(token);
    }

    @GetMapping(value = "/auth/logout")
    public ResultBean refreshAndGetAuthenticationToken() {
        String refreshedToken = authService.refresh(getToken());
        return ResultUtil.SUCCESS(refreshedToken);
    }

    @PostMapping(value = "${jwt.route.authentication.register}")
    public ResultBean register(@RequestBody User addedUser) throws AuthenticationException {
        return ResultUtil.SUCCESS(authService.register(addedUser));
    }
}
